package me.zk.practice1.hw;

import java.util.Arrays;
import java.util.Scanner;

public class HWBJ08 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String s = scanner.nextLine();

        String[] strs = s.split(",");
        int total = scanner.nextInt();

        if (strs.length < 3) {
            System.out.println(-1);
            return;
        }
        int[] m = Arrays.stream(strs).mapToInt(Integer::parseInt).toArray();

        if (total <= m[0]) {
            System.out.println(-1);
            return;
        }
        int max = 0;
        // 固定两个指针
//        for (int i = 0; i < m.length - 2; i++) {
//            for (int j = i+2; j < m.length; j++) {
//                int sum = m[i]+m[i+1]+m[j];
//                if (sum < total) {
//                    max = Math.max(sum,max);
//                }
//            }
//        }
        int l = 0;
        int r = m.length-1;
        int i = l+1;
        while (l < r) {
            int sum = m[l] + m[i] + m[r];
            if (sum >= total) {
                r--;
            } else {
                max = Math.max(max,sum);
                if (i<r) {
                    i++;
                } else {
                    l++;
                    i = l+1;
                }
            }
        }

        System.out.println(max==0? -1:max);
    }

}
